const express = require('express');
const OSS = require('ali-oss');
const dotenv = require('dotenv');
const cors = require('cors');
const mysql = require('mysql2/promise');
const path = require('path');
const { pool, initializeDatabase } = require('./db');

// 加载环境变量
dotenv.config();

const app = express();
app.use(express.json());
app.use(cors());

// 检查必要的环境变量是否存在
const requiredEnvVars = [
    'OSS_REGION',
    'OSS_ACCESS_KEY_ID',
    'OSS_ACCESS_KEY_SECRET',
    'OSS_BUCKET',
    'DB_HOST',
    'DB_PORT',
    'DB_USERNAME',
    'DB_PASSWORD',
    'DB_DATABASE'
];

for (const envVar of requiredEnvVars) {
    if (!process.env[envVar]) {
        console.error(`缺少必要的环境变量: ${envVar}`);
        process.exit(1);
    }
}

// OSS客户端配置
try {
    var client = new OSS({
        region: process.env.OSS_REGION,
        accessKeyId: process.env.OSS_ACCESS_KEY_ID,
        accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
        bucket: process.env.OSS_BUCKET,
    });
} catch (error) {
    console.error('初始化 OSS 客户端失败:', error);
    process.exit(1);
}

// 服务器启动时初始化数据库
(async () => {
    try {
        await initializeDatabase();
    } catch (error) {
        console.error('初始化数据库失败:', error);
        process.exit(1);
    }
})();

// 生成上传用的预签名URL
app.get('/api/upload-url', async (req, res) => {
    try {
        const { filename, contentType } = req.query;
        if (!filename || !contentType) {
            return res.status(400).json({ error: '文件名和内容类型是必需的' });
        }

        // 生成唯一文件名
        const key = `uploads/${Date.now()}-${filename}`;

        // 生成预签名URL，有效期1小时
        const url = client.signatureUrl(key, {
            method: 'PUT',
            expires: 3600,
            'Content-Type': contentType
        });

        // 构建完整的OSS访问URL
        const ossDomain = `https://${process.env.OSS_BUCKET}.${process.env.OSS_REGION}.aliyuncs.com`;
        const fullImageUrl = `${ossDomain}/${key}`;

        res.json({
            uploadUrl: url,
            fileKey: key,
            fullImageUrl: fullImageUrl,  // 返回完整URL给前端
            expiresIn: 3600
        });
    } catch (error) {
        console.error('生成预签名URL失败:', error);
        res.status(500).json({ error: '生成预签名URL失败' });
    }
});

// 生成带签名的OSS URL（新添加的辅助函数）
function generateSignedUrl(imageKey, expires = 3600) {
    try {
        return client.signatureUrl(imageKey, {
            method: 'GET',
            expires: expires
        });
    } catch (error) {
        console.error('生成带签名URL失败:', error);
        return null;
    }
}

// 定义/api/reviews路由
app.post('/api/reviews', async (req, res) => {
    console.log('请求体内容:', req.body);
    const { userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imageKeys } = req.body;

    // 数据验证逻辑
    if (!userId ||!restaurantName ||!rating ||!reviewText) {
        return res.status(400).json({ error: '缺少必要参数' });
    }

    let connection;
    try {
        connection = await pool.getConnection();
        // 开启事务
        await connection.beginTransaction();

        const insertReviewQuery = `
            INSERT INTO restaurant (user_id, user_name, restaurant_name, restaurant_location, dish_name, rating, review_text)
            VALUES (?,?,?,?,?,?,?)
        `;

        const [result] = await connection.query(insertReviewQuery, [userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText]);

        const reviewId = result.insertId;

        // 保存图片URL到数据库（修改部分）
        let insertImageQueries = [];
        if (Array.isArray(imageKeys)) {
            insertImageQueries = imageKeys.map((imageKey) => {
                // 生成带签名的URL（有效期1小时）
                const signedImageUrl = generateSignedUrl(imageKey);
                
                if (!signedImageUrl) {
                    throw new Error(`生成图片 ${imageKey} 的带签名URL失败`);
                }
                
                const insertImageQuery = `
                    INSERT INTO review_images (review_id, image_url)
                    VALUES (?,?)
                `;
                return connection.query(insertImageQuery, [reviewId, signedImageUrl]);
            });
        }

        console.log('insertImageQueries:', insertImageQueries);

        await Promise.all(insertImageQueries);

        // 提交事务
        await connection.commit();

        res.json({ id: reviewId, message: '评价提交成功' });
    } catch (error) {
        // 发生错误时回滚事务
        if (connection) {
            await connection.rollback();
        }
        console.error('插入评价数据失败:', error);
        console.error('insertImageQueries:', insertImageQueries); // 打印插入查询语句数组
        res.status(500).json({ error: '插入评价数据失败' });
    } finally {
        if (connection) {
            connection.release();
        }
    }
});

app.use(express.static(path.join(__dirname, 'public')));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在http://localhost:${PORT}`);
});    